import wepy from 'wepy';
import util from './util';
import md5 from './md5';
import cache from '../tools/cache'
import config from '../config/global'
const API_SECRET_KEY = 'play.he29.com';
const TIMESTAMP = util.getCurrentTime();
const SIGN = md5.hex_md5((TIMESTAMP + API_SECRET_KEY).toLowerCase());

const wxRequest = async(params = {}, url, fn,loading) => {
    if(loading){
        wepy.showToast({
            title: '加载中',
            icon: 'loading'
        });
    }
    let data = params || {};
    data.sign = SIGN;
    data.time = TIMESTAMP;
    data.openid = cache.get('user_openid');
    data.uid = cache.get('user_uid');
    data.token = cache.get('user_token');
    data.webtype = config.webType
    let res = await wepy.request({
        url: url,
        method: 'POST',
        data: data,
        header: {'Content-Type': 'application/x-www-form-urlencoded'},
        success: function (d) {
            fn && fn(d.data)
        }
    });
    if(loading) {
        wepy.hideToast();
    }
};


const fileRequest = async(params = {},path, url, fn) => {
    wepy.showToast({
        title: '上传中',
        icon: 'loading'
    });
    let data = params || {};
    data.sign = SIGN;
    data.time = TIMESTAMP;
    data.openid = cache.get('user_openid');
    data.uid = cache.get('user_uid');
    data.token = cache.get('user_token');
    wx.uploadFile({
        url: url,
        filePath:path,
        name: 'file',
        formData:data,
        header: {
            'content-type': 'multipart/form-data'
        },
        success:function (res) {
            fn && fn (res)
        },
        fail:function (res) {}
    });
    wepy.hideToast();
};

module.exports = {
    wxRequest,
    fileRequest
}
